#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

struct Stu{
    char level;
    string s;
    string examinationRoomNumber;
    string examDate;
    int id;
    int grade;
}stu[100000];

int cmp1(Stu s1,Stu s2){
    if(s1.grade==s2.grade)    return s1.s<s2.s;
	return s1.grade>s2.grade;
}

struct Room{
	string roomid;
	int num;
}room[100000];

int cmp2(Room s1,Room s2){
    if(s1.num==s2.num)    return s1.roomid<s2.roomid;
	return s1.num>s2.num;
}

signed main()
{
    int n,m;
    cin>>n>>m;
    for(int i=0;i<n;i++){
        string s;
        cin>>s>>stu[i].grade;
        stu[i].level = s[0];
        stu[i].s = s;
		stu[i].examinationRoomNumber = s.substr(1,3);
		stu[i].examDate = s.substr(4,6);
		stu[i].id = stoi(s.substr(10,3)); 
    }
    sort(stu,stu+n,cmp1);
    for(int i=0;i<m;i++){
    	cout<<"Case "<<i+1<<": ";
    	int t;
    	cin>>t;
    	cout<<t<<" ";
    	int flag = 0;
    	if(t==1){
    		char c;
    		cin>>c;
    		cout<<c<<"\n";
    		for(int j=0;j<n;j++){
    			if(stu[j].level==c){
    				cout<<stu[j].s<<" "<<stu[j].grade<<"\n";
    				flag = 1;
				}
			}
		}
		else if(t==2){
			string roomNum;
			cin>>roomNum;
			cout<<roomNum<<"\n";
			int stuNum = 0,gradeSum = 0;
			for(int j=0;j<n;j++){
				if(stu[j].examinationRoomNumber==roomNum){
					stuNum++;
					gradeSum += stu[j].grade;
					flag = 1;
				}
			}
			if(stuNum)	cout<<stuNum<<" "<<gradeSum<<"\n";
		}
		else if(t==3){
			string date;
			cin>>date;
			cout<<date<<"\n";
			map<string,int> ma;
			for(int j=0;j<n;j++){
				if(stu[j].examDate==date){
					ma[stu[j].examinationRoomNumber]++;
				}
			}
			int cnt = 0;
			for(auto it:ma){
				room[cnt].roomid = it.first;
				room[cnt++].num = it.second;
			}
			sort(room,room+cnt,cmp2);
			for(int j=0;j<cnt;j++){
				cout<<room[j].roomid<<" "<<room[j].num<<"\n";
				flag = 1;
			}
		}
		if(!flag)	cout<<"NA\n";
	}
    return 0;
}
